import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFiles,
  HttpException,
  HttpStatus,
  All,
  Query,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { Express } from 'express';
import { MusicService } from './music.service';
import { GetListDto } from './dto/music.dto';
@Controller('music')
export class MusicController {
  constructor(private musicService: MusicService) {}
  @Post('upload')
  @UseInterceptors(
    FilesInterceptor('files', null, {
      fileFilter(req, file, callback) {
        const allowedExtensions = /\.(mp3|acc|ogg|wav|flac|ncm)$/;
        const isAllow = allowedExtensions.test(file.originalname);
        if (isAllow) {
          callback(null, true);
        } else {
          callback(
            new HttpException('上传格式错误', HttpStatus.BAD_REQUEST),
            false,
          );
        }
      },
    }),
  )
  async update(@UploadedFiles() files: Express.Multer.File[]) {
    if (!files.length) throw new HttpException('上传数量不能为0', 400);
    try {
      // 先收集所有异步操作的结果
      const results = await Promise.all(
        files.map((item) => this.musicService.upLoad(item)),
      );

      // 再判断所有结果是否都为 true
      const final = results.every((result) => result);

      if (final) {
        return '上传成功';
      } else {
        return '部分文件上传失败';
      }
    } catch (error) {
      throw error; // 注意：最好返回标准化的错误信息，而非直接返回错误对象
    }
  }

  @All('get_list')
  @UsePipes(new ValidationPipe({ transform: true }))
  getList(@Query() query: GetListDto) {
    return this.musicService.getList(query);
  }

  @All('search')
  serchMusic(@Query('keywords') keywords: string) {
    return this.musicService.search(keywords);
  }
}
